package com.sparrow.rpc.socket.init;

import com.sparrow.rpc.socket.codec.RpcDecoder;
import com.sparrow.rpc.socket.codec.RpcEncoder;
import com.sparrow.rpc.socket.codec.RpcLengthFieldBasedFrameDecoder;
import com.sparrow.rpc.socket.handler.RpcServerHandler;
import com.sparrow.socket.tcp.handler.TcpIdleStateHandler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.timeout.IdleStateHandler;

public class RpcServerInitializer extends ChannelInitializer<Channel> {

    private RpcServerHandler rpcServerHandler;

    @Override
    protected void initChannel(Channel channel) throws Exception {
        ChannelPipeline pipeline = channel.pipeline();
        pipeline.addLast(new RpcEncoder());
        // === 心跳与空闲检测 ===
        // 60 秒无读事件触发 IdleStateEvent.READER_IDLE
        pipeline.addLast(new IdleStateHandler(60, 0, 0));
        pipeline.addLast(new TcpIdleStateHandler());
        pipeline.addLast(new RpcLengthFieldBasedFrameDecoder(Integer.MAX_VALUE));
        pipeline.addLast(new RpcDecoder());
        pipeline.addLast(rpcServerHandler);
    }

    public void setRpcServerHandler(RpcServerHandler rpcServerHandler) {
        this.rpcServerHandler = rpcServerHandler;
    }
}
